package com.jackrain.nea.wms.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jackrain.nea.config.Resources;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.wms.api.BaseDelCmd;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySession;
import com.jackrain.nea.web.service.QueryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Set;

@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version="1.0", group = "wms")
public class BaseDelCmdImpl extends CommandAdapter implements BaseDelCmd{


    @Autowired
    private QueryService queryService;

    @Override
    public ValueHolder execute(QuerySession querySession) throws NDSException {
        ValueHolder vh;
        DefaultWebEvent event = querySession.getEvent();
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(event.getParameterValue("param"),"yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue),Feature.OrderedField);

        // 获取isdelmtable 判断是否删除主表
        Boolean isdelmtable = param.getBoolean("isdelmtable");
        if (isdelmtable) {
            // 删除主表
            BaseDelCmdImpl baseDelCmd = ApplicationContextHandle.getBean(BaseDelCmdImpl.class);
            vh = baseDelCmd.tranDelete(param,querySession);
        }else{
            // 删除明细表
            vh = deleteItem(param,querySession);
        }
        return vh;
    }

    // 带事务整表删除(头表明细表都删除)
    @Transactional(rollbackFor = NDSException.class)
    public ValueHolder tranDelete(JSONObject param,QuerySession querySession){
        // 常量
        String tabItem = "tabitem";

        ValueHolder vh = new ValueHolder();


        // 获取主表id objid
        Long objid = param.getLong("objid");
        // 主表不为空 主表操作
        if (objid != null) {
            try {
                // 先删除明细再删除头表 判断是否只删除主表
                if (param.containsKey(tabItem)){
                    // 删除明细表
                    deleteItem(param,querySession);
                }
            } catch (NDSException e) {
                vh.put("code", -1);
                vh.put("message", e.toJsonException().get("msg"));
                return vh;
            }
            //删除头表
            JSONObject whereKeys = new JSONObject();
            whereKeys.put("ID",objid);
            HashMap map = new HashMap();
            map.put("tableName",param.getString("table"));
            map.put("whereKeys",whereKeys);
            queryService.commandDelete(map);
        }
        vh.put("code",0);
        vh.put("message", Resources.getMessage("SUCCESS",querySession.getLocale()));
        return vh;
    }

    /**
     * 不带事务，只删除明细表
     * @param param json参数
     * @param querySession querySession
     * @return ValueHolder
     */
    private ValueHolder deleteItem(JSONObject param,QuerySession querySession){
        ValueHolder vh = new ValueHolder();
        // 当前系统时间
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        // 获取明细表json
        JSONObject tableItem = param.getJSONObject("tabitem");

        // 删除成功条数
        int successCount = 0;

        // 遍历头表下所有明细表
        Set<String> keySets = tableItem.keySet();
        for (String key: keySets) {
            JSONArray joItem = tableItem.getJSONArray(key);

            // 明细表不为空
            if (joItem != null && joItem.size() > 0) {
                // 返回值DATA
                JSONArray dataArrayJson = new JSONArray();
                //
                for (int j = 0; j < joItem.size(); j++) {
                    try {
                        // 删除明细表
                        JSONObject whereKeys = new JSONObject();
                        whereKeys.put("ID",joItem.getLong(j));
                        HashMap sTableMap = new HashMap();
                        sTableMap.put("tableName",key);
                        sTableMap.put("whereKeys",whereKeys);
                        queryService.commandDelete(sTableMap);
                        successCount++;
                    } catch (NDSException e) {
                        JSONObject dataJson = new JSONObject();
                        dataJson.put("id", joItem.getLong(j));
                        dataJson.put("code", "-1");
                        dataJson.put("message", e.toJsonException().get("msg"));
                        dataArrayJson.add(dataJson);
                    }
                }
                if(dataArrayJson.size() > 0){
                    vh.put("data", dataArrayJson);
                    vh.put("code",-1);
                    vh.put("message",Resources.getMessage("失败",querySession.getLocale()));
                }else{
                    vh.put("code",0);
                    vh.put("message",Resources.getMessage("成功",querySession.getLocale()));
                }
            }
        }


        if (successCount > 0) {

            // 更新主表修改时间
            JSONObject setKeys = new JSONObject();
            // 添加修改人
            setKeys.put("MODIFIERID", querySession.getUser().getId().longValue());
            setKeys.put("MODIFIEDDATE", timestamp);
            JSONObject whereKeys = new JSONObject();
            whereKeys.put("ID",param.getLongValue("objid"));
            // 执行mapper更新
            HashMap updateMap = new HashMap();
            updateMap.put("tableName",param.getString("table"));
            updateMap.put("setKeys",setKeys);
            updateMap.put("whereKeys",whereKeys);
            queryService.commandUpdate(updateMap);
        }

        return vh;
    }

}
